package com.yonyou.gmmc.dealerApp.api.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.marketing.common.constants.BusinessConstant;
import org.marketing.common.constants.CodeConstant;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.dto.freeTime.FreeTimeDto;
import org.marketing.common.dto.maintain.MaintainDto;
import org.marketing.common.dto.maintain.MaintainFrecordDto;
import org.marketing.common.dto.maintain.RepairBookParamDto;
import org.marketing.common.dto.maintain.RepairBookTimeDto;
import org.marketing.common.dto.maintain.SosHelpDto;
import org.marketing.common.dto.search.DealerAppSearchDto;
import org.marketing.common.exception.ServiceAppException;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.service.rest.RestServiceConstant;
import org.marketing.common.util.CommonUtils;
import org.marketing.common.util.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.support.json.JSONUtils;
import com.github.pagehelper.PageHelper;
import com.ibm.icu.util.Calendar;
import com.yonyou.gmmc.dealerApp.api.dao.FreeTimeDao;
import com.yonyou.gmmc.dealerApp.api.dao.TtReservationMapper;
import com.yonyou.gmmc.dealerApp.api.dao.TtSoshelpMapper;
import com.yonyou.gmmc.dealerApp.api.entity.MaintainFrecordPO;

import net.sf.json.JSONObject;

/**
 * @author kaihua 由于其他提供服务的微服务接口文档不完整，为了赶进度，目前所有实现放在本微服务自身中实现。
 *         后续有时间整理各个提供服务的微服务开放的功能接口之后，再通过调用其他微服务功能的方式调用功能
 *
 */
@Service
@Transactional
public class CallMaintainService {
	private Logger logger = Logger.getLogger(CallMaintainService.class);

	@Autowired
	private TtReservationMapper maintainmDao;
	@Autowired
	private TtSoshelpMapper sosHelpDao;
	@Autowired
	private FreeTimeDao freeTimeDao;
	@Autowired
	private CallService callServiceInterface;

	/**
	 * 取得养修预约信息
	 * 
	 * @param dealerAppSearchDto
	 * @return
	 */
	public Map<String, Object> getMaintainInfoList(DealerAppSearchDto dealerAppSearchDto) {
		List<MaintainDto> list = getMaintainInfoListForSer(dealerAppSearchDto);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
		resultMap.put(ResultMsgConstants.ERR_MSG, "");
		resultMap.put("maintainList", list);

		return resultMap;
	}

	private List<MaintainDto> getMaintainInfoListForSer(DealerAppSearchDto dealerAppSearchDto)
			throws ServiceAppException, ServiceBizException {

		try {
			PageHelper.startPage(dealerAppSearchDto.getPageNo(), BusinessConstant.PAGE_SIZE);
			List<MaintainDto> list = maintainmDao.getMaintainInfoList(dealerAppSearchDto);
			if (null != list && !list.isEmpty()) {
				for (MaintainDto mDto : list) {
					String bookDate = DateUtil.formateDate(mDto.getReseApplStartTime(), "yyyy-MM-dd");

					List<FreeTimeDto> freList = getFreeTimeCludeWorkStation(mDto.getDealerCode(), bookDate,
							mDto.getAppointType());
					if (null != freList && !freList.isEmpty()) {
						for (FreeTimeDto freeT : freList) {
							// 数据不完整直接跳过。
							if (StringUtils.isEmpty(freeT.getBeginTime()) || StringUtils.isEmpty(freeT.getEndTime())) {
								continue;
							}
							Date begin = DateUtil.dateFormat(bookDate + " " + freeT.getBeginTime() + ":00:00",
									"yyyy-MM-dd HH:mm:ss");
							Date end = DateUtil.dateFormat(bookDate + " " + freeT.getEndTime() + ":00:00",
									"yyyy-MM-dd HH:mm:ss");
							// 预约申请时间在两个时间区间之内。
							if (DateUtil.beforDate(begin, mDto.getReseApplStartTime())
									&& DateUtil.afterDate(end, mDto.getReseApplStartTime())) {
								if (null != freeT.getSpareStationNum() && freeT.getSpareStationNum() <= 0) {
									// 【满】
									mDto.setWarningText(BusinessConstant.MAINTAIN_WARING);
								}
							}

						}
					}

				}
			}

			return list;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceAppException(e.getMessage(), e);
		}

	}

	/**
	 * 
	 * 取得空余时间-包含工位信息<br>
	 * <I>经销商自身维护的包含工位信息</I>
	 * 
	 * @author WangHuicheng
	 * @date 2016年12月7日
	 * @param dealerCode
	 * @param bookDate
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<FreeTimeDto> getFreeTimeCludeWorkStation(String dealerCode, String bookDate, String appointType) {
		try {
			this.logger.info(this.getClass().getName() + ":getFreeTimeCludeWorkStation:begin");
			List<FreeTimeDto> list = null;

			RepairBookParamDto repairBookParamDto = new RepairBookParamDto();
			repairBookParamDto.setDealerCode(dealerCode);
			repairBookParamDto.setBookDate(bookDate);
			repairBookParamDto.setBookingType(appointType);
			repairBookParamDto.setSystemId(BusinessConstant.SYSTEM_ID);
			this.logger.info(CommonUtils.toString(repairBookParamDto));
			Map<String, Object> result = null;
			try {
				result = callServiceInterface.getFreeTimeCludeWorkStation(repairBookParamDto);
			} catch (Exception e) {
				this.logger.error(e.getMessage(), e);
			}
			if (null != result
					&& StringUtils.equals("1", result.get(RestServiceConstant.REST_BUSINESS_STATUS).toString())) {
				list = new ArrayList<FreeTimeDto>();
				List<RepairBookTimeDto> bookTimeList = (List<RepairBookTimeDto>) result
						.get(RestServiceConstant.REST_BUSINESS_OBJECT);
				for (int i = 0; i < bookTimeList.size(); i++) {
					String timeString = JSONUtils.toJSONString(bookTimeList.get(i));
					JSONObject obj = JSONObject.fromObject(timeString);
					RepairBookTimeDto repairBookTimeDto = (RepairBookTimeDto) JSONObject.toBean(obj,
							RepairBookTimeDto.class);
					FreeTimeDto freeTimeDto = new FreeTimeDto();
					BeanUtils.copyProperties(repairBookTimeDto, freeTimeDto);
					list.add(freeTimeDto);
				}
			} else {
				list = freeTimeDao.getFreeTime(dealerCode);
			}
			return list;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceAppException(e.getMessage(), e);
		}
	}

	/**
	 * 保存养修预约跟进记录
	 * 
	 * @param maintainFrecordDto
	 * @return
	 */
	public Map<String, Object> saveTestDrivingAppointFrecord(MaintainFrecordDto maintainFrecordDto) {
		maintainFrecordDto = saveMaintainAppointFrecordForSer(maintainFrecordDto);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
		resultMap.put("tlReservationFollowRecodeId", maintainFrecordDto.getTlreservationFollowRecodeId());
		resultMap.put(ResultMsgConstants.ERR_MSG, "");
		return resultMap;
	}

	private MaintainFrecordDto saveMaintainAppointFrecordForSer(MaintainFrecordDto maintainFrecordDto)
			throws ServiceAppException, ServiceBizException {
		if (!isExistMaintainAppoint(maintainFrecordDto.getResnId())) {
			throw new ServiceAppException("the record is not exist:" + maintainFrecordDto.getResnId(),
					new Exception("the record is not exist:" + maintainFrecordDto.getResnId()));
		}
		try {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());

			maintainFrecordDto.setCreateBy(maintainFrecordDto.getUserId());
			maintainFrecordDto.setCreateDate(calendar.getTime());
			MaintainFrecordPO maintainFrecordPO = new MaintainFrecordPO();

			BeanUtils.copyProperties(maintainFrecordDto, maintainFrecordPO);
			// 不是预约确认的情况，更新跟进记录里面都是预约跟进
			if (null == maintainFrecordDto.getApplyStatus()
					|| CodeConstant.MAINTAIN_FOLLOW_STATUS_CONFIRM != maintainFrecordDto.getApplyStatus().intValue()) {
				maintainFrecordPO.setAppointmentStatus(CodeConstant.DMAINTAIN_FOLLOW_STATUS_FOLLOW);
			} else {
				maintainFrecordPO.setAppointmentStatus(CodeConstant.MAINTAIN_FOLLOW_STATUS_CONFIRM);
			}
			maintainFrecordPO.setCreateBy(maintainFrecordDto.getSalesConsultantId());
			maintainFrecordPO.setFollowDate(calendar.getTime());

			maintainmDao.insertMaintainFrecord(maintainFrecordPO);

			maintainFrecordDto.setTlreservationFollowRecodeId(maintainFrecordPO.getTlreservationFollowRecodeId());

			return maintainFrecordDto;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceAppException(e.getMessage(), e);
		}

	}
	/**
     * 
    * 判断养修预约记录是否存在
    * @author WangHuicheng
    * @date 2016年11月25日
    * @param resnId
    * @return
    * @throws ServiceAppException
    * @throws ServiceBizException
     */
    private boolean isExistMaintainAppoint(Long resnId) throws ServiceAppException,
                                                                          ServiceBizException {
        try {
            List<MaintainDto> list  = maintainmDao.queryMaintainDataById(resnId);

            if (null != list && !list.isEmpty()) {
                return true;
            }
            return false;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceAppException(e.getMessage(), e);
        }

    }

	public Map<String, Object> updateMaintainStatus(MaintainFrecordDto maintainFrecordDto) {
		// TODO Auto-generated method stub
		return null;
	}

	public List<SosHelpDto> getSosHelpInfoList(DealerAppSearchDto dealerAppSearchDto) {
		PageHelper.startPage(dealerAppSearchDto.getPageNo().intValue(), BusinessConstant.PAGE_SIZE);
        List<SosHelpDto> list = sosHelpDao.getSosHelpInfoList(dealerAppSearchDto);

        return list;
	}

	public void updateMaintain4rush(MaintainDto maintainDto) {
		try {
            maintainDto.setUpdateDate(new Date());
            this.maintainmDao.updateMaintain4rush(maintainDto);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceAppException(e.getMessage(), e);
        }
	}

	public void updateSosHelp4rush(SosHelpDto sosHelpDto) {
		try {
            sosHelpDto.setUpdateBy(sosHelpDto.getSalesConsultantId().intValue());
            sosHelpDto.setUpdateDate(new Date());
           this.sosHelpDao.updateSosHelp4rush(sosHelpDto);
            
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceAppException(e.getMessage(), e);
        }

	}
	
	/**
     * 
    * 更新一键救援的信息
    * @author WangHuicheng
    * @date 2016年11月28日
    * @param sosHelpDto
	 * @return 
    * @throws ServiceAppException
    * @throws ServiceBizException
     */
    public Map<String, Object> updateSosHelpStatus(SosHelpDto sosHelpDto) throws ServiceAppException, ServiceBizException {
    	if (null == sosHelpDto.getUpdateBy()){
            sosHelpDto.setUpdateBy(sosHelpDto.getSalesConsultantId().intValue());
        }
    	try {
            // 确定救援
            if (StringUtils.equals(CodeConstant.SOSHELP_STATUS_SUPPORTING+"", sosHelpDto.getStatus())){
                sosHelpDto.setSupportDate(new Date());
            }
            // 救援完成
            if (StringUtils.equals(CodeConstant.SOSHELP_STATUS_FINISHED+"", sosHelpDto.getStatus())){
                sosHelpDto.setSupportFinishDate(new Date());
            }
            sosHelpDao.updateSosHelp(sosHelpDto);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceAppException(e.getMessage(), e);
        }
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
        resultMap.put(ResultMsgConstants.ERR_MSG, "");
        return resultMap;

    }

}
